//Documentation complete
/**
 * @author Jason Funk
 * @version 2009FE16
 */

package utilities;

import java.sql.*;

import broker.ConfigFileBroker;

import problemDomain.ErrorBean;
import static problemDomain.ErrorBean.*;
import static problemDomain.ErrorBean.ErrorCode.*;

/**
 * Creates a connection to a MySQL database.
 */
public class MySQLConnection {
	
	/* Public Constants */
	
	/**
	 * Configuration file which stores additional data.
	 */
	public static final String CONFIG_FILE = "config.xml";
	//"D:/My Documents/School/Java/ordrs/res/config.xml";
	
	/* END Public Constants */
	
	
	/* Constants */
	
	private static final String HOSTNAME = "localhost";
	private static final String PORT = "3306";
	private static String USERNAME = null;
	private static String PASSWORD = null;
	private static final String DB_NAME = "ordrsdb";
	
	/* END Constants */
	
	
	/* Static Methods */
	
	/**
	 * Returns a connection to the MySQL database.
	 * @return a <code>Connection</code> to the MySQL database.
	 * @throws ErrorBean when the connection is not available
	 */
	public static Connection createConnection () throws ErrorBean {
		try {
			if (USERNAME == null)
				USERNAME = getUsername();
			if (PASSWORD == null)
				PASSWORD = getPassword();
			
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection(
				"jdbc:mysql://" + HOSTNAME + ':' + PORT + '/' + DB_NAME,
				USERNAME, PASSWORD);
			if (conn == null)
				throwError(
					BROKER_CONNECTION_NOT_AVAILABLE,
					"Connection failed.",
					MySQLConnection.class);
			return conn;
		} catch (SQLException e) {
			throwError(
				BROKER_CONNECTION_NOT_AVAILABLE,
				e.getMessage(),
				MySQLConnection.class);
			return null;
		} catch (ClassNotFoundException e) {
			throwError(
				BROKER_CONNECTION_NOT_AVAILABLE, 
				e.getMessage(), 
				MySQLConnection.class);
			return null;
		}
		
	}
	
	/**
	 * Sets the password field with the password read from the config file.
	 * @throws ErrorBean
	 */
	private static String getPassword() throws ErrorBean {
		ConfigFileBroker cfb = ConfigFileBroker.getBroker();
		return cfb.listAll("password").get(0);
	}
	
	/**
	 * Sets the username field with the user name read from the config file.
	 * @throws ErrorBean
	 */
	private static String getUsername() throws ErrorBean {
		ConfigFileBroker cfb = ConfigFileBroker.getBroker();
		return cfb.listAll("username").get(0);
	}
	
	/* END Static Methods */
}
